package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取用户uri
        String requestURI = request.getRequestURI();
//        log.info("拦截到请求: {}",requestURI);


        //2.放行页面、登录相关的接口（白名单）
        String[] uris = new String[]{
                "/user/login",
                "/user/sendMsg",
                "/common/**",
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };
        boolean check = check(uris,requestURI);

        if (check){
            log.info("放行路径{}",requestURI);
            filterChain.doFilter(request,response);//放行
            return;//终止程序，不让他往下走
        }
        //3.登录成功-彻底放行
        HttpSession session = request.getSession();
        Object empId = session.getAttribute("empId");//(empId)取
        if (empId!=null){

            log.error("线程id={}",Thread.currentThread().getId());
            BaseContext.setId((Long) empId);

            log.info("已登录放行{}",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登录");

        //最后-拦截-响应一个结果
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 路径匹配器
     * @param uris  白名单
     * @param requestURI    test路径
     * @return  如果返回true 放行 false 拦截
     */
    public boolean check(String[] uris,String requestURI){
        AntPathMatcher matcher = new AntPathMatcher();
        for (String uri : uris) {
            boolean match = matcher.match(uri, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
